using HarmonyLib;
using RimWorld;
using System.Collections.Generic;
using Verse;
using Verse.AI;
using UnityEngine;
using System.Reflection.Emit;
using System.Linq;

namespace RimZombieGirl
{

    public static class Pawn_FoodTypePatch
    {
        // 食尸替换
        


        // 食物替换
        [HarmonyPatch(typeof(FoodUtility), nameof(FoodUtility.FoodIsSuitable), new System.Type[] { typeof(Pawn), typeof(ThingDef) })]
        public static class FoodIsSuitable_Extension_Patch
        {
            public static bool Prefix(Pawn p, ThingDef food, ref bool __result)
            {
                // 检查是否有自定义基因组件
                PawnComp_GeneExt comp = p.GetComp<PawnComp_GeneExt>();
                if (comp != null && comp.GetFoodType() != FoodTypeFlags.None)
                {
                    // 使用自定义食物类型进行判断
                    if (p.needs.food == null)
                    {
                        __result = false;
                        return false; // 跳过原方法
                    }
                    
                    // 检查食物是否符合自定义食物类型
                    __result = (comp.GetFoodType() & food.ingestible.foodType) > FoodTypeFlags.None;
                    return false; // 跳过原方法
                }
                
                return true; // 继续执行原方法
            }
        }
    }

    [HarmonyPatch(typeof(Pawn_Thinker))]
    public static class Pawn_Thinker_Patch
    {
        // Patch MainThinkTree getter
        [HarmonyPatch("get_MainThinkTree")]
        [HarmonyPostfix]
        public static void MainThinkTree_Postfix(Pawn_Thinker __instance, ref ThinkTreeDef __result)
        {
            Pawn parent = __instance.pawn;
            PawnComp_GeneExt comp = parent.GetComp<PawnComp_GeneExt>();
            if (comp == null || comp.GetThinkTreeDef() == null)
            {
                return; // No replacement component found, use default behavior
            }
            __result = comp.GetThinkTreeDef();
        }

        // Patch ConstantThinkTree getter
        [HarmonyPatch("get_ConstantThinkTree")]
        [HarmonyPostfix]
        public static void ConstantThinkTree_Postfix(Pawn_Thinker __instance, ref ThinkTreeDef __result)
        {
            Pawn parent = __instance.pawn;
            PawnComp_GeneExt comp = parent.GetComp<PawnComp_GeneExt>();
            if (comp == null || comp.GetConstantThinkTreeDef() == null)
            {
                return; // No replacement component found, use default behavior
            }
            __result = comp.GetConstantThinkTreeDef();
        }
    }

    [HarmonyPatch(typeof(JobGiver_GetFood), "TryGiveJob")]
    public static class JobGiver_GetFood_TryGiveJob_Patch
    {
        [HarmonyTranspiler]
        public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
        {
            var codes = new List<CodeInstruction>(instructions);
            var geneExtMethod = AccessTools.Method(typeof(PawnExts), nameof(PawnExts.GeneExt_CanEatCorpse));
            
            // 根据 IL 代码，局部变量索引：
            // [0] Need_Food food
            // [1] bool flag (allowCorpse 的基础值)
            // [2] FoodPreferability foodPreferability
            // [3] bool desperate
            
            // 查找 IL_00a6: ldloc.1 (加载 flag) 和后面传递给 TryFindBestFoodSourceFor 的位置
            for (int i = 0; i < codes.Count - 5; i++)
            {
                // 查找调用 TryFindBestFoodSourceFor 之前加载 flag 的位置 (IL_00a6: ldloc.1)
                if (codes[i].opcode == OpCodes.Ldloc_1 && // 加载 flag
                    i + 1 < codes.Count && codes[i + 1].opcode == OpCodes.Ldc_I4_0 && // allowSociallyImproper: false
                    i + 2 < codes.Count && codes[i + 2].opcode == OpCodes.Ldloc_2) // 加载 foodPreferability
                {
                    // 在 ldloc.1 之前插入我们的逻辑来修改 flag
                    var insertIndex = i;
                    
                    // 创建跳转标签
                    var skipLabel = new Label();
                    
                    var newInstructions = new List<CodeInstruction>
                    {
                        // 检查 flag 是否已经为 true
                        new CodeInstruction(OpCodes.Ldloc_1), // 加载 flag
                        new CodeInstruction(OpCodes.Brtrue_S, skipLabel), // 如果已经为 true，跳过我们的检查
                        
                        // 检查我们的基因扩展
                        new CodeInstruction(OpCodes.Ldarg_1), // 加载 pawn 参数
                        new CodeInstruction(OpCodes.Call, geneExtMethod), // 调用 GeneExt_CanEatCorpse
                        new CodeInstruction(OpCodes.Brfalse_S, skipLabel), // 如果返回 false，跳过设置
                        
                        // 设置 flag = true
                        new CodeInstruction(OpCodes.Ldc_I4_1), // true
                        new CodeInstruction(OpCodes.Stloc_1), // 存储到 flag (局部变量 1)
                        
                        // 检查 foodPreferability 是否为 Undefined，如果是则设置为 DesperateOnly
                        new CodeInstruction(OpCodes.Ldloc_2), // 加载 foodPreferability
                        new CodeInstruction(OpCodes.Brtrue_S, skipLabel), // 如果不是 Undefined (0)，跳过
                        new CodeInstruction(OpCodes.Ldc_I4_2), // FoodPreferability.DesperateOnly = 2 (根据 IL_0085)
                        new CodeInstruction(OpCodes.Stloc_2), // 存储到 foodPreferability (局部变量 2)
                    };
                    
                    // 设置跳转标签到原始的 ldloc.1 指令
                    codes[insertIndex].labels.Add(skipLabel);
                    
                    codes.InsertRange(insertIndex, newInstructions);
                    break;
                }
            }
            
            return codes;
        }
    }
}